import numpy as np  
import numpy as np  

def otsu_threshold(image):  
    # 将二维列表转换为NumPy数组  
    image_array = np.array(image)  

    # 计算图像的直方图  
    hist, bins = np.histogram(image_array.flatten(), 256, [0, 257])  

    # 计算总的像素点数  
    total_pixels = image_array.size  

    # 计算累积和  
    sum_b = np.cumsum(hist)  

    # 计算累积均值（类间均值）  
    sum_w = np.cumsum(hist * np.arange(0, bins.size-1))  
    mean_b = sum_w / sum_b  

    # 初始化类间方差和阈值  
    var_max = 0  
    threshold = 0  

    # 遍历所有可能的阈值  
    for i in range(1, bins.size):  
        # 计算前景像素点数和背景像素点数  
        w_b = sum_b[i - 1]  
        w_f = total_pixels - w_b  
        # 如果前景或背景没有像素，则跳过  
        if w_b == 0 or w_f == 0:  
            continue  
        # 计算前景和背景的均值  
        mean_f = sum_w[i - 1] / w_b  
        mean_b_current = (sum_w[total_pixels] - sum_w[i - 1]) / w_f  
        # 计算类间方差  
        var_between = w_b * w_f * (mean_b_current - mean_b[i - 1]) ** 2  
        # 如果当前类间方差大于之前的最大值，则更新阈值和最大类间方差  
        if var_between > var_max:  
            var_max = var_between  
            threshold = (bins[i - 1] + bins[i]) // 2  
    return threshold  

# 示例用法  
# 假设你有一个名为 `image_data` 的二维列表，表示灰度图像  
# image_data = [...]  # 这里应该是你的图像数据  
# threshold = otsu_threshold(image_data)  
# print(f"Otsu's threshold: {threshold}")
if __name__=="__main__":
    img=[[0,10,250],[250,100,250],[10,20,10]]
    sbotsu=otsu_threshold(img)
    print(sbotsu)